#include "ImageManager.h"
#include <iostream>

#include "exceptions.h"
#include "qdebug.h"

using namespace std;
using namespace sf;

ImageManager::ImageManager() : m_images()
{

}

ImageManager::~ImageManager()
{
    QMap<QString, ImageRef*>::const_iterator i = m_images.constBegin();
    while(i != m_images.constEnd())
    {
        delete i.value();
        ++i;
    }
}

ImageManager& ImageManager::getInstance()
{
    static ImageManager instance;
    return instance;
}


//DEBUGGING
void ImageManager::printPaths() const
{
    qDebug() << "ImageManager's loaded images :";

    QMap<QString, ImageRef*>::const_iterator i = m_images.constBegin();
    while(i != m_images.constEnd())
	{
        qDebug() << i.key();
        ++i;
	}
}

const Image& ImageManager::getImage(const QString& path)
{
    return getImageRef(path)->image;
}

const QPixmap& ImageManager::getPixmap(const QString& path)
{
    return getImageRef(path)->pixmap;
}

ImageRef* ImageManager::getImageRef(const QString& path)
{
    QMap<QString, ImageRef*>::const_iterator i = m_images.find(path);
    if(i != m_images.end()) //the requested image already exists
    {
        return i.value();
    }
	else	//the requested image hasn't been loaded yet
    {
        //creates the image using the given path
        i = m_images.insert(path, new ImageRef);

        if(i.value()->image.LoadFromFile(path.toStdString()) &&
                i.value()->pixmap.load(path))	//image loading succeeded
		{
            i.value()->image.SetSmooth(false);
            return i.value();
		}
		else
		{
            throw EX_FILE_NOT_FOUND(path);
		}
	}
}
